package com.qms.repast.ui.presenter;

import android.app.Activity;
import android.database.Cursor;

import com.qms.repast.App;
import com.qms.repast.db.CuisineBeanDao;
import com.qms.repast.db.CuisineOrderBeanDao;
import com.qms.repast.entity.resbean.CuisineBean;
import com.qms.repast.entity.resbean.CuisineOrderBean;
import com.qms.repast.module.UserModule;
import com.qms.repast.ui.base.BasePresenter;
import com.qms.repast.ui.view.IOrderReviewView;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 泅渡者
 * @date 2018/10/11 0011
 * @describe: 购物车
 */
public class OrderReviewPresenter extends BasePresenter<IOrderReviewView> {
	private UserModule userModule;
	private List<CuisineBean> cuisineBeans;

	public OrderReviewPresenter (Activity mContext, IOrderReviewView mView) {
		super(mContext, mView);
		this.userModule = new UserModule(mContext);
	}

	/**
	 * 查找选中的所有菜
	 *
	 * @param userId 用户Id
	 * @param shopId 店铺Id
	 */
	public void selectAllItem (String userId, String shopId) {
		//这里查询当前用户   当前店铺下所有的菜品总和
		List<CuisineOrderBean> cuisineOrderBeans = new ArrayList<>();
		String sql = "SELECT _id , USER_ID , SHOP_ID , ITEM_ID , SUM(ITEM_NUM) FROM CUISINE_ORDER_BEAN 	WHERE USER_ID = " + userId + " AND SHOP_ID = " + shopId + " GROUP BY ITEM_ID ORDER BY _id DESC ";
		Cursor cursor = App.getmDaoSession().getDatabase().rawQuery(sql, null);

		if (cursor.moveToFirst()) {
			do {
				CuisineOrderBean cuisineOrderBean = new CuisineOrderBean();
				cuisineOrderBean.setId(cursor.getLong(cursor.getColumnIndex("_id")));
				cuisineOrderBean.setUserId(cursor.getString(cursor.getColumnIndex("USER_ID")));
				cuisineOrderBean.setShopId(cursor.getString(cursor.getColumnIndex("SHOP_ID")));
				cuisineOrderBean.setItemId(cursor.getString(cursor.getColumnIndex("ITEM_ID")));
				cuisineOrderBean.setItemNum(cursor.getInt(cursor.getColumnIndex("SUM(ITEM_NUM)")));
				cuisineOrderBeans.add(cuisineOrderBean);

			}
			while (cursor.moveToNext());
		}

		cursor.close();

		cuisineBeans = new ArrayList<>();
		//根据itemId 查询菜品信息 并将数据赋值过去
		for (int i = 0; i < cuisineOrderBeans.size(); i++) {
			List<CuisineBean> beans = App.getmDaoSession()
					.getCuisineBeanDao()
					.queryBuilder()
					.where(
							CuisineBeanDao.Properties.ItemId.eq(cuisineOrderBeans.get(i).getItemId())
					).list();
			CuisineBean cuisineBean = beans.get(0);
			cuisineBean.setOptNum(cuisineOrderBeans.get(i).getItemNum());
			cuisineBeans.add(cuisineBean);
		}

		if (null != cuisineBeans) {
			mView.updateAllData(cuisineBeans);
		}
	}

	/**
	 * @param userId
	 * @param shopId
	 */
	public void selectItemCount (String userId, String shopId) {
		//在购物车中查找该菜品
		List<CuisineOrderBean> cuisineOrderBeans = App.getmDaoSession()
				.getCuisineOrderBeanDao()
				.queryBuilder()
				.where(
						CuisineOrderBeanDao.Properties.UserId.eq(userId),
						CuisineOrderBeanDao.Properties.ShopId.eq(shopId)
				).list();
		mView.showItemCount(cuisineOrderBeans.size());
	}
}
